﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using UniMana.Utils.Helper;
using UniMana.Utils.Data;
using System.Linq;
using UniMana.Data;

namespace UniMana.Win.Systems
{
    public partial class FrmCreateUser : DevExpress.XtraEditors.XtraForm
    {
        private System_UserInfo m_sui;
        private DataTable m_dtSys_Group;
        private DataTable m_dtSys_User_Rule;
        private DataTable m_dtAllowData;
        private DataTable m_dtNotAllowData;
        
        #region Deleage dữ liệu
        public delegate void PassData(System_UserInfo sui);
        public PassData passData;
        public void DelegateAddRule(DataTable dtSystem_User_Rule)
        {
            if (m_dtSys_User_Rule == null)
            {
                m_dtSys_User_Rule = new DataTable();
            }

            #region khởi tạo DataTable m_dtSys_Group chứa thông tin nhóm của user
            if (m_dtSys_Group == null)
            {
                m_dtSys_Group = new DataTable();
            }
            if (m_dtSys_Group.Columns.Count == 0)
            {
                m_dtSys_Group.Columns.Add("System_GroupKey");
                m_dtSys_Group.Columns.Add("Name");

               // m_dtSys_Group.Columns.Add("Description");
                m_dtSys_Group.AcceptChanges();
            }
            #endregion

            #region Tạo cấu trúc datable m_dtSys_User_Rule
            if (m_dtSys_User_Rule.Columns.Count == 0)
            {
                m_dtSys_User_Rule.Columns.Add("System_UserKey");
                m_dtSys_User_Rule.Columns.Add("System_RuleKey");

                m_dtSys_User_Rule.Columns.Add("RuleID");
                m_dtSys_User_Rule.Columns.Add("RuleName");
                m_dtSys_User_Rule.Columns.Add("RuleNameVi");
                m_dtSys_User_Rule.Columns.Add("ParentID");
                m_dtSys_User_Rule.Columns.Add("Level");
                m_dtSys_User_Rule.Columns.Add("AllowAccess", System.Type.GetType("System.Boolean"));
                m_dtSys_User_Rule.Columns.Add("AllowAdd", System.Type.GetType("System.Boolean"));
                m_dtSys_User_Rule.Columns.Add("AllowDelete", System.Type.GetType("System.Boolean"));
                m_dtSys_User_Rule.Columns.Add("AllowEdit", System.Type.GetType("System.Boolean"));
                m_dtSys_User_Rule.Columns.Add("AllowExport", System.Type.GetType("System.Boolean"));
                m_dtSys_User_Rule.Columns.Add("AllowImport", System.Type.GetType("System.Boolean"));
                m_dtSys_User_Rule.Columns.Add("AllowPrint", System.Type.GetType("System.Boolean"));
                m_dtSys_User_Rule.Columns.Add("AllowSave", System.Type.GetType("System.Boolean"));
            }
            #endregion
            if (dtSystem_User_Rule != null)
            {
                foreach (DataRow row in dtSystem_User_Rule.Rows)
                {
                    DataRow dRow = (from DataRow r in m_dtSys_User_Rule.Rows where r["RuleID"].ToString().ToUpper() == row["RuleID"].ToString().ToUpper() select r).FirstOrDefault();

                    if (dRow == null)
                    {
                        m_dtSys_User_Rule.Rows.Add(new object[] { 
                            m_sui.Properties.System_UserKey,
                            row["System_RuleKey"],
                            row["RuleID"], 
                            row["RuleName"],
                            row["RuleNameVi"], 
                            row["ParentID"],
                            row["Level"], 
                            row["AllowAccess"],
                            row["AllowAdd"], 
                            row["AllowDelete"], 
                            row["AllowEdit"], 
                            row["AllowExport"], 
                            row["AllowImport"], 
                            row["AllowPrint"],
                            row["AllowSave"] });
                        if (int.Parse(row["Level"].ToString()) == -1 && row["RuleID"].ToString() != "common")
                        {
                            m_dtSys_Group.Rows.Add(new object[] { row["RuleID"], row["RuleNameVi"] });
                        }
                    }
                    else
                    {

                        if (int.Parse(row["Level"].ToString()) == 0)
                        {
                            dRow["ParentID"] = "common";
                        }
                        //dRow["System_RuleKey"]= row["System_RuleKey"];
                        dRow["RuleID"] = row["RuleID"];
                        dRow["RuleName"] = row["RuleName"];
                        dRow["RuleNameVi"] = row["RuleNameVi"];

                        dRow["Level"] = row["Level"];
                        dRow["AllowAccess"] = row["AllowAccess"];
                        dRow["AllowAdd"] = row["AllowAdd"];
                        dRow["AllowDelete"] = row["AllowDelete"];
                        dRow["AllowEdit"] = row["AllowEdit"];
                        dRow["AllowExport"] = row["AllowExport"];
                        dRow["AllowImport"] = row["AllowImport"];
                        dRow["AllowPrint"] = row["AllowPrint"];
                        dRow["AllowSave"] = row["AllowSave"];
                    }
                }
            }

            //#region Thêm nhóm chứa các chức năng chung của nhiều group
            //if (m_dtSys_Group.Rows.Count > 1)
            //{
            //    DataRow drcom = (from DataRow r in m_dtSys_User_Rule.Rows where r["RuleID"].ToString().ToUpper() == "common".ToUpper() select r).FirstOrDefault();
            //    if (drcom == null)
            //    {
            //        m_dtSys_User_Rule.Rows.Add(new object[] { 
            //            "", 
            //            "common",
            //            "common", 
            //            "common",
            //            "Cùng thuộc nhiều nhóm", //row["RuleNameVi"], 
            //            "",//row["ParentID"]!="" ?  row["ParentID"] : m_dr[i][0].ToString(),  
            //            -1, 
            //            true,
            //            true, 
            //            true, 
            //            true, 
            //            true, 
            //            true, 
            //            true, 
            //            true });
            //    }
            //}
            //#endregion

            grcInfoUserAndGroup.DataSource = m_dtSys_Group;
            tltPermission.DataSource = m_dtSys_User_Rule;

            m_dtSys_User_Rule.AcceptChanges();
            tltPermission.CollapseAll();
        }

        //public void DelegateAddGroup(DataRow[] dr)
        //{
        //    #region khởi tạo DataTable m_dtSys_Group chứa thông tin nhóm của user
        //    if (m_dtSys_Group == null)
        //    {
        //        m_dtSys_Group = new DataTable();
        //    }
        //    if (m_dtSys_Group.Columns.Count == 0)
        //    {
        //        m_dtSys_Group.Columns.Add("System_GroupKey");
        //        m_dtSys_Group.Columns.Add("Name");

        //        m_dtSys_Group.Columns.Add("Description");
        //        m_dtSys_Group.AcceptChanges();
        //    }
        //    #endregion
           
        //    #region Khởi tạo datatable m_dtSys_User_Rule chứa thông tin quyền của user
        //    if (m_dtSys_User_Rule == null)
        //    {
        //        m_dtSys_User_Rule = new DataTable();
               
        //    }

        //    if (m_dtSys_User_Rule.Columns.Count == 0)
        //    {
        //        m_dtSys_User_Rule.Columns.Add("System_UserKey");
        //        m_dtSys_User_Rule.Columns.Add("System_RuleKey");

        //        m_dtSys_User_Rule.Columns.Add("RuleID");
        //        m_dtSys_User_Rule.Columns.Add("RuleName");
        //        m_dtSys_User_Rule.Columns.Add("RuleNameVi");
        //        m_dtSys_User_Rule.Columns.Add("ParentID");
        //        m_dtSys_User_Rule.Columns.Add("Level");
        //        m_dtSys_User_Rule.Columns.Add("AllowAccess", System.Type.GetType("System.Boolean"));
        //        m_dtSys_User_Rule.Columns.Add("AllowAdd", System.Type.GetType("System.Boolean"));
        //        m_dtSys_User_Rule.Columns.Add("AllowDelete", System.Type.GetType("System.Boolean"));
        //        m_dtSys_User_Rule.Columns.Add("AllowEdit", System.Type.GetType("System.Boolean"));
        //        m_dtSys_User_Rule.Columns.Add("AllowExport", System.Type.GetType("System.Boolean"));
        //        m_dtSys_User_Rule.Columns.Add("AllowImport", System.Type.GetType("System.Boolean"));
        //        m_dtSys_User_Rule.Columns.Add("AllowPrint", System.Type.GetType("System.Boolean"));
        //        m_dtSys_User_Rule.Columns.Add("AllowSave", System.Type.GetType("System.Boolean"));
        //    }
        //    #endregion
           
        //    for (int i = 0; i < dr.Length; i++)
        //    {
        //        m_dtSys_Group.Rows.Add(new object[] { dr[i][0], dr[i][1], dr[i][2]});

        //        DataTable dtGr = System_RuleData.RuleByGroup(new DBSystem(), Convert.ToInt16(dr[i][0])).ToDataTable();

        //        foreach (DataRow row in dtGr.Rows)
        //        {
        //            DataRow dRow = (from DataRow r in m_dtSys_User_Rule.Rows where r["RuleID"].ToString().ToUpper() == row["RuleID"].ToString().ToUpper() select r).FirstOrDefault();

        //            if (dRow == null)
        //            {
        //                m_dtSys_User_Rule.Rows.Add(new object[] { 
        //                m_sui.Properties.System_UserKey, 
        //                row["System_RuleKey"],
        //                row["RuleID"], 
        //                row["RuleName"],
        //                row["RuleNameVi"], 
        //                row["ParentID"], 
        //                row["Level"], 
        //                true,
        //                true, 
        //                true, 
        //                true, 
        //                true, 
        //                true, 
        //                true, 
        //                true });
        //            }
        //            else
        //            {
        //                if ((string)row["ParentID"] == "")
        //                {
        //                    dRow["ParentID"] = "common";
        //                }
        //            }
        //        }

        //        m_dtSys_User_Rule.Rows.Add(new object[] { 
        //                "", 
        //                dr[i][0].ToString(),
        //                dr[i][0].ToString(), 
        //                dr[i][0].ToString(),
        //                dr[i][1].ToString(), //row["RuleNameVi"], 
        //                "",//row["ParentID"]!="" ?  row["ParentID"] : m_dr[i][0].ToString(),  
        //                -1, 
        //                true,
        //                true, 
        //                true, 
        //                true, 
        //                true, 
        //                true, 
        //                true, 
        //                true });
        //    }

        //    m_dtSys_User_Rule.Rows.Add(new object[] { 
        //                "", 
        //                "common",
        //                "common", 
        //                "common",
        //                "Cùng thuộc nhiều nhóm", //row["RuleNameVi"], 
        //                "",//row["ParentID"]!="" ?  row["ParentID"] : m_dr[i][0].ToString(),  
        //                -1, 
        //                true,
        //                true, 
        //                true, 
        //                true, 
        //                true, 
        //                true, 
        //                true, 
        //                true });


        //    grcInfoUserAndGroup.DataSource = m_dtSys_Group;
        //    tltPermission.DataSource = m_dtSys_User_Rule;
        //    m_dtSys_User_Rule.AcceptChanges();
        //}
        //public void DelegateUser(System_UserInfo sui)
        //{

        //    DataTable dt = tltUserAndGroup.DataSource as DataTable;
        //    DataRow dRow = (from DataRow dr in dt.Rows where dr["ID"].ToString().ToUpper() == sui.Properties.System_UserKey.ToString().ToUpper() select dr).FirstOrDefault();
        //    if (dRow != null)
        //    {

        //        dRow["ID"] = sui.Properties.System_UserKey;
        //        dRow["DescName"] = sui.Properties.UserName;
        //        dRow["ParentID"] = sui.Properties.Catalogue_DepartmentKey;
        //        dRow["FullName"] = sui.Properties.FullName;
        //    }
        //    else
        //    {
        //        DataRow dr = dt.NewRow();
        //        dr["ID"] = sui.Properties.System_UserKey;
        //        dr["DescName"] = sui.Properties.UserName;
        //        dr["ParentID"] = sui.Properties.Catalogue_DepartmentKey;
        //        dr["FullName"] = sui.Properties.FullName;
        //        dt.Rows.Add(dr);
        //    }
        //}
        #endregion

        public FrmCreateUser(System_UserInfo _sui = null)
        {

            InitializeComponent();
            lueCatalogue_Department.GetData(Catalogue_DepartmentData.GetList());
            if (_sui != null)
            {
                m_sui = _sui;
                txtUserName.Text = m_sui.Properties.UserName;
                txtFullName.Text = m_sui.Properties.FullName;
                txtPassword.Text = m_sui.Properties.Password.Decrypt();
               

                txtPasswordConfirm.Text = m_sui.Properties.Password.Decrypt();
                //lciPasswordConfirm.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
                //lciPassword.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
                if (m_sui.Properties.Personnel_PersonnelKey != null)
                {
                    
                    DataRow drPersionel = System_UserData.GetUserOfPersionel(m_sui.Properties.Personnel_PersonnelKey.Value).ToDataTable().Rows[0];
                    txtPersionalID.Text = drPersionel["ID"].ToString();
                    txtFullName.Text = drPersionel["LastName"].ToString() + drPersionel["Name"].ToString();
                    lueCatalogue_Department.EditValue = drPersionel["Catalogue_DepartmentKey"];

                }

                moeDescription.Text = m_sui.Properties.Description;
                //lueCatalogue_Department.EditValue = m_sui.Properties.Catalogue_DepartmentKey;
                dteDateBegin.EditValue = m_sui.Properties.BeginDay;
                dteDateEnd.EditValue = m_sui.Properties.EndDay;
                ckeChangePassword.Checked = Convert.ToBoolean(m_sui.Properties.ChangePassword);
                ckeDisableAccount.Checked = Convert.ToBoolean(m_sui.Properties.DisableAccount);
                ckeNerverExpire.Checked = Convert.ToBoolean(m_sui.Properties.NerverExpire);
                LoadData();
            }
            else 
            {
                m_sui = null;
                m_dtNotAllowData = Catalogue_DepartmentData.GetList().ToDataTable();
                grcNotAllowData.DataSource = m_dtNotAllowData;

            }

            if (ckeNerverExpire.Checked == true)
            {
                dteDateBegin.Enabled = false;
                dteDateEnd.Enabled = false;
            }

        }

        public void LoadData()
        {

            m_dtSys_Group = System_GroupData.GetGroupByUserKey(new DBMain(), m_sui.Properties.System_UserKey).ToDataTable();
            this.grcInfoUserAndGroup.DataSource = m_dtSys_Group;
            m_dtSys_Group.AcceptChanges();

            LoadRule();

            m_dtNotAllowData = System_Rule_DepartmentData.GetNotAllowByUserKey(new DBMain(), m_sui.Properties.System_UserKey).ToDataTable();
            m_dtAllowData = System_Rule_DepartmentData.GetAllowByUserKey(new DBMain(), m_sui.Properties.System_UserKey).ToDataTable();
            
            grcAllowData.DataSource = m_dtAllowData;
            grcNotAllowData.DataSource = m_dtNotAllowData;

            m_dtAllowData.AcceptChanges();
            m_dtNotAllowData.AcceptChanges();

        }
        public void LoadRule()
        {

            DataTable dtTemp = System_User_RuleData.GetRuleByUser(m_sui.Properties.System_UserKey).ToDataTable();

            m_dtSys_User_Rule = new DataTable();
            #region Tạo cấu trúc datable m_dtSys_User_Rule
            if (m_dtSys_User_Rule.Columns.Count == 0)
            {
                m_dtSys_User_Rule.Columns.Add("System_UserKey");
                m_dtSys_User_Rule.Columns.Add("System_RuleKey");

                m_dtSys_User_Rule.Columns.Add("RuleID");
                m_dtSys_User_Rule.Columns.Add("RuleName");
                m_dtSys_User_Rule.Columns.Add("RuleNameVi");
                m_dtSys_User_Rule.Columns.Add("ParentID");
                m_dtSys_User_Rule.Columns.Add("Level");
                m_dtSys_User_Rule.Columns.Add("AllowAccess", System.Type.GetType("System.Boolean"));
                m_dtSys_User_Rule.Columns.Add("AllowAdd", System.Type.GetType("System.Boolean"));
                m_dtSys_User_Rule.Columns.Add("AllowDelete", System.Type.GetType("System.Boolean"));
                m_dtSys_User_Rule.Columns.Add("AllowEdit", System.Type.GetType("System.Boolean"));
                m_dtSys_User_Rule.Columns.Add("AllowExport", System.Type.GetType("System.Boolean"));
                m_dtSys_User_Rule.Columns.Add("AllowImport", System.Type.GetType("System.Boolean"));
                m_dtSys_User_Rule.Columns.Add("AllowPrint", System.Type.GetType("System.Boolean"));
                m_dtSys_User_Rule.Columns.Add("AllowSave", System.Type.GetType("System.Boolean"));
            }

            #endregion

            if (m_dtSys_Group != null)
            {
                foreach(DataRow drg in m_dtSys_Group.Rows)
                {
                    DataTable dtGr = System_RuleData.RuleByGroup(new DBMain(), Convert.ToInt16(drg[0])).ToDataTable();

                    foreach (DataRow row in dtGr.Rows)
                    {
                        DataRow dRow = (from DataRow r in m_dtSys_User_Rule.Rows where r["RuleID"].ToString().ToUpper() == row["RuleID"].ToString().ToUpper() select r).FirstOrDefault();
                        if (dRow == null)
                        {
                            m_dtSys_User_Rule.Rows.Add(new object[] { 
                            m_sui.Properties.System_UserKey, //Để trống userkey
                            row["System_RuleKey"],
                            row["RuleID"], 
                            row["RuleName"],
                            row["RuleNameVi"], 
                            (string)row["ParentID"]!="" ?  row["ParentID"] : drg[0].ToString(),  
                            row["Level"], 
                            true,
                            true, 
                            true, 
                            true, 
                            true, 
                            true, 
                            true, 
                            true });
                        }
                        else
                        {
                            if ((string)row["ParentID"] == "")
                            {
                                dRow["ParentID"] = "common";
                            }
                        }
                    }

                    m_dtSys_User_Rule.Rows.Add(new object[] { 
                        m_sui.Properties.System_UserKey, 
                        drg[0].ToString(),
                        drg[0].ToString(), 
                        drg[0].ToString(),
                        drg[1].ToString(), //row["RuleNameVi"], 
                        "",//row["ParentID"]!="" ?  row["ParentID"] : m_dr[i][0].ToString(),  
                        -1, 
                        true,
                        true, 
                        true, 
                        true, 
                        true, 
                        true, 
                        true, 
                        true });
                }

                //#region Thêm nhóm chứa các chức năng chung của nhiều group
                //if (m_dtSys_Group.Rows.Count > 1)
                //{
                //    m_dtSys_User_Rule.Rows.Add(new object[] { 
                //        "", 
                //        "common",
                //        "common", 
                //        "common",
                //        "Cùng thuộc nhiều nhóm", //row["RuleNameVi"], 
                //        "",//row["ParentID"]!="" ?  row["ParentID"] : m_dr[i][0].ToString(),  
                //        -1, 
                //        true,
                //        true, 
                //        true, 
                //        true, 
                //        true, 
                //        true, 
                //        true, 
                //        true });
                //}
                //#endregion
                foreach (DataRow row in dtTemp.Rows)
                {
                    DataRow dRow = (from DataRow r in m_dtSys_User_Rule.Rows where r["RuleID"].ToString().ToUpper() == row["RuleID"].ToString().ToUpper() select r).FirstOrDefault();
                    if (dRow == null)
                    {
                        //System_User_RuleInfo suri = new System_User_RuleInfo(m_sui.Properties.System_UserKey, Guid.Parse(row["System_RuleKey"].ToString()));
                        //suri.Delete();
                    }
                    else
                    {
                        dRow["RuleID"] = row["RuleID"];
                        dRow["RuleName"] = row["RuleName"];
                        dRow["RuleNameVi"] = row["RuleNameVi"];
                       // dRow["ParentID"] = row["ParentID"];
                       // dRow["Level"] = row["Level"];
                        dRow["AllowAccess"] = row["AllowAccess"];
                        dRow["AllowAdd"] = row["AllowAdd"];
                        dRow["AllowDelete"] = row["AllowDelete"];
                        dRow["AllowEdit"] = row["AllowEdit"];
                        dRow["AllowExport"] = row["AllowExport"];
                        dRow["AllowImport"] = row["AllowImport"];
                        dRow["AllowPrint"] = row["AllowPrint"];
                        dRow["AllowSave"] = row["AllowSave"];
                    }
                }
            }

            this.tltPermission.DataSource = m_dtSys_User_Rule;
            m_dtSys_User_Rule.AcceptChanges();


        }

        private void btnCreate_Click(object sender, EventArgs e)
        {
            if (DataValidated())
            {
                this.Validate();
                #region Lưu thông tin User
                // Ma hoa MD5 Password
                if (m_sui == null||m_sui.Properties.UserName==null)
                {

                    if (System_UserData.UserValidated(txtUserName.Text))
                    {
                        m_sui = new System_UserInfo();
                        m_sui.Properties.System_UserKey = Guid.NewGuid();
                        m_sui.Properties.Password = txtPassword.Text.Encrypt();
                        m_sui.Properties.UserName = this.txtUserName.Text.Trim();
                        m_sui.Properties.FullName = this.txtFullName.Text;
                        
                        if (System_UserData.GetPersionelKey(this.txtPersionalID.Text).ToString() != UniMana.Utils.Configs.DefaultConfig.EMPTY_GUID)
                        {
                            m_sui.Properties.Personnel_PersonnelKey = System_UserData.GetPersionelKey(this.txtPersionalID.Text.Trim());
                        }
                        else
                        {
                            DialogResult dlgResult = MessageBox.Show("Không tồn tại nhân viên trong hệ thống. Để tiếp tục nhấn OK hoặc kiểm tra lại nhấn Cancel.", "Cảnh báo", MessageBoxButtons.OKCancel);
                            if (dlgResult == System.Windows.Forms.DialogResult.Cancel)
                                return;
                        }
                        
                        m_sui.Properties.Description = this.moeDescription.Text;
                        m_sui.Properties.ChangePassword = ckeChangePassword.Checked;
                        m_sui.Properties.NerverExpire = this.ckeNerverExpire.Checked;
                        if (this.ckeNerverExpire.Checked == false)
                        {
                            m_sui.Properties.BeginDay = (DateTime)this.dteDateBegin.EditValue;
                            m_sui.Properties.EndDay = (DateTime)this.dteDateEnd.EditValue;
                        }
                        m_sui.Properties.DisableAccount = ckeChangePassword.Checked;

                        //if (this.lueCatalogue_Department.EditValue != null)
                        //{
                        //    m_sui.Properties.Catalogue_DepartmentKey = int.Parse(this.lueCatalogue_Department.EditValue.ToString());
                        //}
                        //else
                        //{
                        //    MessageBox.Show("Bạn chưa chọn phòng ban cho người dùng");
                        //    return;
                        //}
                    }
                    else
                    {
                        MessageBox.Show("Tên tài khoản đã tồn tài. Vui long chọn tên khác");
                        return;
                    }
                }
                else
                {

                        m_sui.Properties.UserName = this.txtUserName.Text.Trim();
                        m_sui.Properties.FullName = this.txtFullName.Text;
                        m_sui.Properties.Password = txtPassword.Text.Encrypt();
                        if (System_UserData.GetPersionelKey(this.txtPersionalID.Text).ToString() != UniMana.Utils.Configs.DefaultConfig.EMPTY_GUID)
                        {
                            m_sui.Properties.Personnel_PersonnelKey = System_UserData.GetPersionelKey(this.txtPersionalID.Text.Trim());
                        }
                        else
                        {
                            DialogResult dlgResult = MessageBox.Show("Không tồn tại nhân viên trong hệ thống. Để tiếp tục nhấn OK hoặc kiểm tra lại nhấn Cancel.", "Cảnh báo", MessageBoxButtons.OKCancel);
                            if (dlgResult == System.Windows.Forms.DialogResult.Cancel)
                                return;
                        }

                        m_sui.Properties.Description = this.moeDescription.Text;
                        m_sui.Properties.ChangePassword = ckeChangePassword.Checked;
                        m_sui.Properties.NerverExpire = this.ckeNerverExpire.Checked;

                        if (this.ckeNerverExpire.Checked == false)
                        {
                            m_sui.Properties.BeginDay = (DateTime)this.dteDateBegin.EditValue;
                            m_sui.Properties.EndDay = (DateTime)this.dteDateEnd.EditValue;
                        }
                        m_sui.Properties.DisableAccount = ckeChangePassword.Checked;

                        //if (this.lueCatalogue_Department.EditValue != null)
                        //{
                        //    m_sui.Properties.Catalogue_DepartmentKey = int.Parse(this.lueCatalogue_Department.EditValue.ToString());
                        //}
                        //else
                        //{
                        //    MessageBox.Show("Bạn chưa chọn phòng ban cho người dùng");
                        //    return;
                        //}
                   
                }


                    //Lay cac truong tren from dua vao bang dbo.System_User 
               
                #endregion
            }

            #region Lưu nhóm của user

            if (m_dtSys_Group != null)
            {
                m_sui.Save();
                //foreach (DataRow dr in m_dtSys_Group.Rows)
                //{
                //    System_User_GroupInfo sugi = new System_User_GroupInfo(m_sui.Properties.System_UserKey, int.Parse(dr["System_RuleKey"].ToString()));
                //    sugi.Save();
                //}

                #region Lưu quyền User
               
                foreach (DataRow dr in m_dtSys_User_Rule.Rows)
                {
                    if (int.Parse(dr["Level"].ToString()) != -1)
                    {
                        System_User_RuleInfo suri = new System_User_RuleInfo(m_sui.Properties.System_UserKey, Guid.Parse(dr["System_RuleKey"].ToString()));

                        if (dr["AllowAccess"] != DBNull.Value)
                            suri.Properties.AllowAccess = Convert.ToBoolean(dr["AllowAccess"]);
                        if (dr["AllowAdd"] != DBNull.Value)
                            suri.Properties.AllowAdd = Convert.ToBoolean(dr["AllowAdd"]);
                        if (dr["AllowDelete"] != DBNull.Value)
                            suri.Properties.AllowDelete = Convert.ToBoolean(dr["AllowDelete"]);
                        if (dr["AllowEdit"] != DBNull.Value)
                            suri.Properties.AllowEdit = Convert.ToBoolean(dr["AllowEdit"]);
                        if (dr["AllowExport"] != DBNull.Value)
                            suri.Properties.AllowExport = Convert.ToBoolean(dr["AllowExport"]);
                        if (dr["AllowImport"] != DBNull.Value)
                            suri.Properties.AllowImport = Convert.ToBoolean(dr["AllowImport"]);
                        if (dr["AllowPrint"] != DBNull.Value)
                            suri.Properties.AllowPrint = Convert.ToBoolean(dr["AllowPrint"]);
                        if (dr["AllowSave"] != DBNull.Value)
                            suri.Properties.AllowSave = Convert.ToBoolean(dr["AllowSave"]);

                        suri.Save();
                    }
                    else
                    {
                        if (dr["System_RuleKey"].ToString() != "common")
                        {
                            System_User_GroupInfo sugi = new System_User_GroupInfo(m_sui.Properties.System_UserKey, int.Parse(dr["System_RuleKey"].ToString()));
                            sugi.Save();
                        }
                    }
                }
                #endregion

                if (passData != null)
                {
                    passData(m_sui);
                }
                Close();
            }
            else
            {
                MessageBox.Show("Bạn phải thiết lập nhóm cho người dùng");

            }
            #endregion
            #region Lưu quyền truy cập dữ liệu khoa
                SaveAllowData();
            #endregion
            //ResetControl();
       }
        
        private bool DataValidated()
        {

            bool validated = false;
            if (txtUserName.Text == "" || txtPassword.Text == "" || txtPasswordConfirm.Text == "")
            {
                MessageBox.Show("Tài khoản và mật khẩu không hợp lệ. Vui lòng kiểm tra lại");
            }
            else
            {
                if (txtPassword.Text != txtPasswordConfirm.Text)
                {
                    MessageBox.Show("Mật khẩu xác nhận không đúng. Vui lòng kiểm tra lại");

                }
                else
                {
                    if (ckeNerverExpire.Checked == false)
                    {
                       
                        if (dteDateBegin.EditValue != null && dteDateEnd.EditValue != null && DateTime.Parse(dteDateBegin.EditValue.ToString()) <= DateTime.Parse(dteDateEnd.EditValue.ToString()) && DateTime.Parse(dteDateEnd.EditValue.ToString()) >= DateTime.Now)
                        {
                            validated = true;
                        }
                        else
                        {
                            MessageBox.Show("Vui lòng kiểm tra lại. Ngày hết hạn >= ngày bắt đầu >=ngày hiện hành");
                        }
                    }
                    else
                    {
                        validated = true;
                    }
                }
            }

            return validated;
        }

        private void ResetControl()
        {
            this.Text = "Tạo người dùng mới";
            txtFullName.Text = "";
            txtUserName.Text = "";
            txtPassword.Text = "";
            txtPasswordConfirm.Text = "";
            txtPersionalID.Text = "";
            lciPassword.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always;
            lciPasswordConfirm.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always;
            moeDescription.Text = "";
            ckeChangePassword.Checked = true;
            ckeDisableAccount.Checked = false;
            ckeNerverExpire.Checked = false;

            m_dtNotAllowData = System_Rule_DepartmentData.GetNotAllowByUserKey(new DBMain(), m_sui.Properties.System_UserKey).ToDataTable();
            m_dtAllowData = System_Rule_DepartmentData.GetAllowByUserKey(new DBMain(), m_sui.Properties.System_UserKey).ToDataTable();
            
            grcAllowData.DataSource = m_dtAllowData;
            grcNotAllowData.DataSource = m_dtNotAllowData;

            m_dtAllowData.AcceptChanges();
            m_dtNotAllowData.AcceptChanges();
        }

        private void ckeNerverExpire_CheckedChanged(object sender, EventArgs e)
        {
            if (ckeNerverExpire.Checked == false)
            {
                this.dteDateBegin.Enabled = true;
                this.dteDateEnd.Enabled = true;
            }
            else
            {
                this.dteDateBegin.Enabled = false;
                this.dteDateEnd.Enabled = false;
            }
        }

        private void btnAddGroup_Click(object sender, EventArgs e)
        {
            if (m_sui == null) m_sui = new System_UserInfo();
            int[] group = new int[0];
            if (m_dtSys_Group != null)
            {
                group = new int[m_dtSys_Group.Rows.Count];
                int i = 0;

                foreach (DataRow dr in m_dtSys_Group.Rows)
                {
                    group[i] = int.Parse(dr["System_GroupKey"].ToString());
                }
            }

            FrmGroupList f = new FrmGroupList(m_sui.Properties.System_UserKey, group);
            f.passData = new FrmGroupList.PassData(DelegateAddRule);
            f.StartPosition = FormStartPosition.CenterParent;
            f.ShowDialog();

        }

        private void btnRemoveGroup_Click(object sender, EventArgs e)
        {
            //try
            //{
                DataTable dtGroupRule = System_Group_RuleData.GetByGroup(int.Parse(grvMain.GetFocusedRowCellValue("System_GroupKey").ToString())).ToDataTable();

                foreach (DataRow row in dtGroupRule.Rows)
                {
                    DataRow dRow = (from DataRow r in m_dtSys_User_Rule.Rows where r["System_RuleKey"].ToString().ToUpper() == row["System_RuleKey"].ToString().ToUpper() select r).FirstOrDefault();
                    if (dRow != null)
                    {
                        if (dRow["ParentID"].ToString() != "common")
                        {
                            System_User_RuleInfo suri = new System_User_RuleInfo(m_sui.Properties.System_UserKey, Guid.Parse(row["System_RuleKey"].ToString()));
                            suri.Delete();
                            suri.Save();
                        }
                    }
                    else
                    {
                        //System_Group_RuleInfo f = new System_Group_RuleInfo(int.Parse(row["System_GroupKey"].ToString()), Guid.Parse(row["System_RuleKey"].ToString()));
                        //f.Delete();
                        //f.Save();
                    }
                   
                }

                System_User_GroupInfo sugi = new System_User_GroupInfo(m_sui.Properties.System_UserKey, int.Parse(grvMain.GetFocusedRowCellValue("System_GroupKey").ToString()));
                
                DataRow drGroup = (from DataRow dr in m_dtSys_Group.Rows where dr["System_GroupKey"].ToString() == grvMain.GetFocusedRowCellValue("System_GroupKey").ToString() select dr).FirstOrDefault();
                
                m_dtSys_Group.Rows.Remove(drGroup);
                sugi.Delete();
                sugi.Save();

                LoadRule();
                //m_dtSys_User_Rule = System_User_RuleData.GetRuleByUser(m_sui.Properties.System_UserKey).ToDataTable();
               // tltPermission.DataSource = m_dtSys_User_Rule;
            //}
            //catch { }
        }

        private void btnSaveAndAdd_Click(object sender, EventArgs e)
        {
            if (DataValidated())
            {
                this.Validate();
                #region Lưu thông tin User
                // Ma hoa MD5 Password
                if (m_sui == null && System_UserData.UserValidated(txtUserName.Text))
                {
                    m_sui = new System_UserInfo();
                    //Lay cac truong tren from dua vao bang dbo.System_User
                    m_sui.Properties.System_UserKey = Guid.NewGuid();

                   
                }
                m_sui.Properties.Password = txtPassword.Text.Encrypt();
                m_sui.Properties.UserName = this.txtUserName.Text;
                m_sui.Properties.FullName = this.txtFullName.Text;

                if (System_UserData.GetPersionelKey(this.txtPersionalID.Text).ToString() != UniMana.Utils.Configs.DefaultConfig.EMPTY_GUID)
                {
                    m_sui.Properties.Personnel_PersonnelKey = System_UserData.GetPersionelKey(this.txtPersionalID.Text);
                }
                else
                {
                    DialogResult dlgResult = MessageBox.Show("Không tồn tại nhân viên trong hệ thống. Để tiếp tục nhấn OK hoặc kiểm tra lại nhấn Cancel.", "Cảnh báo",MessageBoxButtons.OKCancel);
                    if(dlgResult == System.Windows.Forms.DialogResult.Cancel)
                       return;
                }
                
                m_sui.Properties.Description = this.moeDescription.Text;
                m_sui.Properties.ChangePassword = ckeChangePassword.Checked;
                m_sui.Properties.NerverExpire = this.ckeNerverExpire.Checked;
                if (this.ckeNerverExpire.Checked == false)
                {
                    m_sui.Properties.BeginDay = (DateTime)this.dteDateBegin.EditValue;
                    m_sui.Properties.EndDay = (DateTime)this.dteDateEnd.EditValue;
                }

                m_sui.Properties.DisableAccount = ckeChangePassword.Checked;

                //if (this.lueCatalogue_Department.EditValue != null)
                //{
                //    m_sui.Properties.Catalogue_DepartmentKey = int.Parse(this.lueCatalogue_Department.EditValue.ToString());
                //}
                //else
                //{
                //    MessageBox.Show("Bạn chưa chọn phòng ban cho người dùng");
                //    return;
                //}
                



                #endregion

                #region Lưu nhóm của user

                if (m_dtSys_Group != null)
                {
                    m_sui.Save();
                    foreach (DataRow dr in m_dtSys_Group.Rows)
                    {
                        System_User_GroupInfo sugi = new System_User_GroupInfo(m_sui.Properties.System_UserKey, int.Parse(dr["System_GroupKey"].ToString()));
                        sugi.Save();
                    }
                    #region Lưu quyền User
                    //foreach (DataRow dr in dtSys_User_Rule.GetChanges(DataRowState.Deleted).Rows)
                    //{
                    //    System_User_RuleInfo suri = new System_User_RuleInfo(m_sui.Properties.System_UserKey, Guid.Parse(dr["System_RuleKey"].ToString()));
                    //    suri.Delete();
                    //}

                    foreach (DataRow dr in m_dtSys_User_Rule.Rows)
                    {
                        if (int.Parse(dr["Level"].ToString()) != -1)
                        {
                            System_User_RuleInfo suri = new System_User_RuleInfo(m_sui.Properties.System_UserKey, Guid.Parse(dr["System_RuleKey"].ToString()));

                            if (dr["AllowAccess"] != DBNull.Value)
                                suri.Properties.AllowAccess = Convert.ToBoolean(dr["AllowAccess"]);
                            if (dr["AllowAdd"] != DBNull.Value)
                                suri.Properties.AllowAdd = Convert.ToBoolean(dr["AllowAdd"]);
                            if (dr["AllowDelete"] != DBNull.Value)
                                suri.Properties.AllowDelete = Convert.ToBoolean(dr["AllowDelete"]);
                            if (dr["AllowEdit"] != DBNull.Value)
                                suri.Properties.AllowEdit = Convert.ToBoolean(dr["AllowEdit"]);
                            if (dr["AllowExport"] != DBNull.Value)
                                suri.Properties.AllowExport = Convert.ToBoolean(dr["AllowExport"]);
                            if (dr["AllowImport"] != DBNull.Value)
                                suri.Properties.AllowImport = Convert.ToBoolean(dr["AllowImport"]);
                            if (dr["AllowPrint"] != DBNull.Value)
                                suri.Properties.AllowPrint = Convert.ToBoolean(dr["AllowPrint"]);
                            if (dr["AllowSave"] != DBNull.Value)
                                suri.Properties.AllowSave = Convert.ToBoolean(dr["AllowSave"]);

                            suri.Save();
                        }
                        else
                        {
                            if (dr["System_RuleKey"].ToString() != "common")
                            {
                                System_User_GroupInfo sugi = new System_User_GroupInfo(m_sui.Properties.System_UserKey, int.Parse(dr["System_RuleKey"].ToString()));
                                sugi.Save();
                            }
                        }
                    }
                    #endregion

                    if (passData != null)
                    {
                        passData(m_sui);
                    }
                    ResetControl();//Close();
                }
                else
                {
                    MessageBox.Show("Bạn phải thiết lập nhóm cho người dùng");

                }
                #endregion

                #region Lưu quyền truy cập dữ liệu khoa
                SaveAllowData();
                #endregion

            }

        }
        /// <summary>
        /// Thêm quyền truy cập dữ liệu
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAddPerData_Click(object sender, EventArgs e)
        {
            
            if (grvNotAllowData.GetFocusedRow() != null)
            {
                //m_dtAllowData = grcAllowData.DataSource as DataTable;
                if (m_dtAllowData == null) m_dtAllowData = new DataTable();
                if (m_dtAllowData.Columns.Count == 0)
                {
                    m_dtAllowData.Columns.Add("Catalogue_DepartmentKey");
                    m_dtAllowData.Columns.Add("Name");
                    m_dtAllowData.Columns.Add("System_UserKey");
                    m_dtAllowData.Columns.Add("AllowEdit");
                    m_dtAllowData.Columns.Add("AllowDel");
                    m_dtAllowData.Columns.Add("AllowAdd");
                    m_dtAllowData.Columns.Add("AllowAccess");
                }
               
                DataRow drAllowData = m_dtAllowData.NewRow();
                drAllowData["Catalogue_DepartmentKey"] = grvNotAllowData.GetFocusedDataRow()["Catalogue_DepartmentKey"];
                drAllowData["Name"] = grvNotAllowData.GetFocusedDataRow()["Name"];
                if (m_sui != null)
                {
                    drAllowData["System_UserKey"] = m_sui.Properties.System_UserKey;
                }

                drAllowData["AllowEdit"] = true;
                drAllowData["AllowDel"] = true;
                drAllowData["AllowAdd"] = true;
                drAllowData["AllowAccess"] = true;

                m_dtAllowData.Rows.Add(drAllowData);

                m_dtNotAllowData.Rows.RemoveAt(grvNotAllowData.GetFocusedDataSourceRowIndex());

                grcAllowData.DataSource = m_dtAllowData;
                grcNotAllowData.DataSource = m_dtNotAllowData;

            }

        }
        /// <summary>
        /// Xóa quyền truy cập dữ liệu
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnRemovePerData_Click(object sender, EventArgs e)
        {
            if (grvNotAllowData.GetFocusedRow() == null)
            {
                if (m_dtNotAllowData.Columns.Count == 0)
                {
                    m_dtNotAllowData.Columns.Add("Catalogue_DepartmentKey");
                    m_dtNotAllowData.Columns.Add("Name");
                }

                DataRow drNotAllowData = m_dtNotAllowData.NewRow();

                drNotAllowData["Catalogue_DepartmentKey"] = grvAllowData.GetFocusedDataRow()["Catalogue_DepartmentKey"];
                drNotAllowData["Name"] = grvAllowData.GetFocusedDataRow()["Name"];

                m_dtNotAllowData.Rows.Add(drNotAllowData);
                m_dtAllowData.Rows.RemoveAt(grvAllowData.GetFocusedDataSourceRowIndex());
            }
            
            grvAllowData.DeleteSelectedRows();

            grcAllowData.DataSource = m_dtAllowData;
            grcNotAllowData.DataSource = m_dtNotAllowData;
        }

        #region Lưu quyền truy cập dữ liệu theo khoa
        private void SaveAllowData()
        {
            if (m_dtAllowData != null)
            {
                if (m_dtAllowData.GetChanges(DataRowState.Added) != null)
                {
                    foreach (DataRow dr in m_dtAllowData.GetChanges(DataRowState.Added).Rows)
                    {
                        System_Rule_DepartmentInfo srdi = new System_Rule_DepartmentInfo(Guid.Parse(dr["System_UserKey"].ToString()), int.Parse(dr["Catalogue_DepartmentKey"].ToString()));
                        if (dr["System_UserKey"].ToString()=="")
                        {
                                srdi.Properties.System_UserKey = m_sui.Properties.System_UserKey;
                        }
                        if (dr["AllowAccess"].ToString() != "")
                            srdi.Properties.AllowAccess = bool.Parse(dr["AllowAccess"].ToString());
                        srdi.Save();
                    }
                }

                if (m_dtAllowData.GetChanges(DataRowState.Deleted) != null)
                {
                    foreach (DataRow dr in m_dtAllowData.GetChanges(DataRowState.Deleted).Rows)
                    {
                        System_Rule_DepartmentInfo srdi = new System_Rule_DepartmentInfo(Guid.Parse(dr["System_UserKey", DataRowVersion.Original].ToString()), int.Parse(dr["Catalogue_DepartmentKey", DataRowVersion.Original].ToString()));
                        if (dr["System_UserKey", DataRowVersion.Original].ToString() == "")
                        {
                            srdi.Properties.System_UserKey = m_sui.Properties.System_UserKey;
                        }
                        srdi.Delete();
                        srdi.Save();
                    }
                }

                if (m_dtAllowData.GetChanges(DataRowState.Modified) != null)
                {
                    foreach (DataRow dr in m_dtAllowData.GetChanges(DataRowState.Modified).Rows)
                    {
                        System_Rule_DepartmentInfo srdi = new System_Rule_DepartmentInfo(Guid.Parse(dr["System_UserKey"].ToString()), int.Parse(dr["Catalogue_DepartmentKey"].ToString()));
                        if (dr["System_UserKey"].ToString() == "")
                        {
                            srdi.Properties.System_UserKey = m_sui.Properties.System_UserKey;
                        }
                        if (dr["AllowEdit"].ToString() != "") srdi.Properties.AllowEdit = bool.Parse(dr["AllowEdit"].ToString());

                        if (dr["AllowDel"].ToString() != "") srdi.Properties.AllowDel = bool.Parse(dr["AllowDel"].ToString());
                        if (dr["AllowAdd"].ToString() != "") srdi.Properties.AllowAdd = bool.Parse(dr["AllowAdd"].ToString());
                        if (dr["AllowAccess"].ToString() != "") srdi.Properties.AllowAccess = bool.Parse(dr["AllowAccess"].ToString());
                    }
                }
            }

        }
        #endregion

        
    }
}